﻿using System;
using System. Windows;
using Microsoft. Phone. Scheduler;
using NextApp. WP7. Models;
using NextApp. WP7. UnionLib;
using WP7_JsonLib;

namespace NextApp. WP7. Scheduled
{
    public sealed class ScheduledProcess
    {
        #region Singleton
        private static readonly ScheduledProcess instance = new ScheduledProcess( );
        public static ScheduledProcess Instance { get { return instance; } }
        private ScheduledProcess( ) 
        {
            EventSingleton. Instance. OnGetPostsCompleted += (s, e) =>
                {
                    RenewBlogs renewBlogs = e. Tag as RenewBlogs;
                    if ( renewBlogs != null )
                    {
                        this. StartPeriodicAgent(renewBlogs);
                    }
                };
        }
        #endregion

        private PeriodicTask getNewBlogsTask;
        private string periodicTaskName = "GetNewBlogs_Makingware";

        private void StartPeriodicAgent( RenewBlogs renewBlogs)
        {
            System. Diagnostics. Debug. WriteLine("开始后台呼叫   {0}", DateTime. Now);
            getNewBlogsTask = ScheduledActionService. Find(periodicTaskName) as PeriodicTask;
            if ( getNewBlogsTask != null )
            {
                RemoveAgent(periodicTaskName);
            }
            getNewBlogsTask = new PeriodicTask(periodicTaskName)
            {
                Description = JsonUtil. JsonSerialize<RenewBlogs>(renewBlogs),
            };
            try
            {
                ScheduledActionService. Add(getNewBlogsTask);
                ScheduledActionService. LaunchForTest(periodicTaskName, renewBlogs. Duration);
            }
            catch ( InvalidOperationException exception )
            {
                if ( exception. Message. Contains("BNS Error: The action is disabled") )
                {
                    MessageBox. Show("Background agents for this application have been disabled by the user.");
                }
            }
        }

        private void RemoveAgent(string name)
        {
            try
            {
                ScheduledActionService. Remove(name);
            }
            catch ( Exception ex)
            {
                System. Diagnostics. Debug. WriteLine(ex. Message);
            }
        }
    }
}
